#import "LoginViewController.h"
#import "EMError.h"
#import "wangjimimaViewController.h"
#import "ShareMethods.h"

@interface LoginViewController ()<IChatManagerDelegate,UITextFieldDelegate,LoginDelegate>

@property (weak, nonatomic) IBOutlet UITextField *usernameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UISwitch *useIpSwitch;


- (IBAction)doRegister:(id)sender;
- (IBAction)doLogin:(id)sender;
- (IBAction)useIpAction:(id)sender;

@end

@implementation LoginViewController

@synthesize usernameTextField = _usernameTextField;
@synthesize passwordTextField = _passwordTextField;
@synthesize registerButton = _registerButton;
@synthesize loginButton = _loginButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupForDismissKeyboard];
    _usernameTextField.delegate = self;
    
    [_useIpSwitch setOn:[[EaseMob sharedInstance].chatManager isUseIp] animated:YES];
    
    NSLog(@"LoginVC*****2016-03-14");
    
    UILabel* titleLb=[[UILabel alloc] initWithFrame:CGRectMake(120, 0, 80, 40)];
    titleLb.text=@"登录";
    titleLb.font = [UIFont systemFontOfSize:22];
    titleLb.textColor=[UIColor whiteColor];
    titleLb.textAlignment=NSTextAlignmentCenter;
    titleLb.backgroundColor=[UIColor clearColor];
    self.navigationItem.titleView=titleLb;
    
    CGRect frame_img= CGRectMake(0,(44-19)/2,19,19);
    UIImageView* backView=[[UIImageView alloc] initWithFrame:frame_img];
    backView.image=[UIImage imageNamed:@"back2016"];
    CGRect frameBtn= CGRectMake(0, 0,50, 44);
    UIButton* homeBtn= [[UIButton alloc] initWithFrame:frameBtn];
    [homeBtn addTarget:self action:@selector(backFn) forControlEvents:UIControlEventTouchUpInside];
    [homeBtn addSubview:backView];
    UIBarButtonItem* barHomeBtn= [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    self.navigationItem.leftBarButtonItem=barHomeBtn;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(doRegisterFn)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    _bgview1.layer.cornerRadius = 15;
    _bgview1.layer.borderColor = [UIColor colorWithRed:235/255.0 green:93/255.0 blue:94/255.0 alpha:1.0].CGColor;
    _bgview1.layer.borderWidth = 1.0f;
    
    _bgview2.layer.cornerRadius = 15;
    _bgview2.layer.borderColor = [UIColor colorWithRed:235/255.0 green:93/255.0 blue:94/255.0 alpha:1.0].CGColor;
    _bgview2.layer.borderWidth = 1.0f;
    
    _WXLogin.layer.cornerRadius = 25/2;
    _WXLogin.layer.borderColor = [UIColor colorWithRed:235/255.0 green:93/255.0 blue:94/255.0 alpha:1.0].CGColor;
    _WXLogin.layer.borderWidth = 1.0f;
    
    _QQLogin.layer.cornerRadius = 25/2;
    _QQLogin.layer.borderColor = [UIColor colorWithRed:235/255.0 green:93/255.0 blue:94/255.0 alpha:1.0].CGColor;
    _QQLogin.layer.borderWidth = 1.0f;
    
    [_loginButton setBackgroundImage:[UIImage imageNamed:@"loginButton"] forState:0];
    _LoginBtn.layer.cornerRadius = 18;
    _LoginBtn.layer.masksToBounds = YES;
    //
    int h=[Tools getScreenHeight];
    
    
    [_remenberPW setTitle:@"记住密码" forState:UIControlStateNormal];
    [_remenberPW setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_remenberPW.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [_remenberPW setImage:[UIImage imageNamed:@"notSelect"] forState:UIControlStateNormal];
    [_remenberPW setImage:[UIImage imageNamed:@"Selected"] forState:UIControlStateSelected];
    [_remenberPW setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
    [_remenberPW.imageView setContentMode:UIViewContentModeScaleAspectFit];
    _remenberPW.selected = true;
    [_remenberPW addTarget:self action:@selector(remenberPW_:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_remenberPW];
    
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString *username = [ud objectForKey:@"username"];
    NSString *password = [ud objectForKey:@"password"];
    if (username.length !=0) {
        _usernameTextField.text = username;
    }
    if (password.length !=0) {
        _passwordTextField.text = password;
    }
    
    
    
    [_forgotPW setTitle:@"忘记密码" forState:UIControlStateNormal];
    [_forgotPW setTitleColor:[UIColor colorWithRed:235/255.0 green:93/255.0 blue:94/255.0 alpha:1.0] forState:UIControlStateNormal];
    [_forgotPW.titleLabel setFont:[UIFont systemFontOfSize:15]];
    //[btn2 setImage:[UIImage imageNamed:@"notSelect"] forState:UIControlStateNormal];
    //[btn2 setImage:[UIImage imageNamed:@"Selected"] forState:UIControlStateSelected];
    [_forgotPW setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
    //[_forgotPW.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [_forgotPW addTarget:self action:@selector(forgotPW_) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_forgotPW];
    
    
    
    UIButton*  regBtn=[[UIButton alloc] initWithFrame:CGRectMake(50, h-100-64, 220, 25)];
    [regBtn addTarget:self action:@selector(doRegisterFn) forControlEvents:UIControlEventTouchUpInside];
    //[self.view addSubview:regBtn];
    
    UILabel* dontRegLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, 25)];
    dontRegLb.text=@"还没有注册夜店中国账号?";
    dontRegLb.font=[UIFont systemFontOfSize:13];
    dontRegLb.textColor=[UIColor blackColor];
    //[regBtn addSubview:dontRegLb];
    //
    UILabel* lijiRegLb=[[UILabel alloc] initWithFrame:CGRectMake(160, 0, 60, 25)];
    lijiRegLb.text=@"立即注册";
    lijiRegLb.font=[UIFont systemFontOfSize:13];
    lijiRegLb.textColor=[UIColor redColor];
    //[regBtn addSubview:lijiRegLb];
    
    [ShareMethods shareInstance].delegate = self;
}

- (IBAction)WXLogin_shareMethod:(id)sender {
    //[ShareMethods shareInstance].delegate = self;
    //[self showHudInView:self.view hint:NSLocalizedString(@"login.ongoing", @"Is Login...")];
    [[ShareMethods shareInstance]loginByWx:self];
}

- (IBAction)QQLogin_shareMethod:(id)sender {
    //[self showHudInView:self.view hint:NSLocalizedString(@"login.ongoing", @"Is Login...")];
    [[ShareMethods shareInstance]loginByQQ];
}

-(void)ThirdPartyLoginDelegate:(ThirdPartyType)Type LoginState:(LoginState)loginState PInfo:(NSDictionary *)pInfo OpenID:(NSString *)openID{
    //[self hideHud];
    NSLog(@"第三方登录pInfo：%@  openID:%@",pInfo,openID);
    if (Type == QQ) {
        switch (loginState) {
            case LoginSuccessful:
                //[[THud sharedInstance]showText:@"登录成功"];
//                [self loginThirdParty:openID NickName:[pInfo objectForKey:@"nickname"] Type:QQ Avatar:[pInfo objectForKey:@"figureurl_qq_2"]];
                NSLog(@"QQ登录成功");
                [self thirdPartyLoginByOpenID:openID avatar:[pInfo objectForKey:@"figureurl_qq_2"] nickName:[pInfo objectForKey:@"nickname"] loginType:@"1" userType:@"1"];
                break;
                
            case LoginUserCancel:
                NSLog(@"QQ取消了登录");
                //[[THud sharedInstance]showText:@"您取消了QQ登录" Delay:2.0];
                break;
                
            case LoginNotNetwork:
                //[[THud sharedInstance]showText:@"网络异常，请检查网络连接"];
                NSLog(@"QQ网络异常");
                break;
                
            case LoginFailure:
                //[[THud sharedInstance]showText:@"登录失败"];
                NSLog(@"QQ登录失败");
                break;
                
            default:
                break;
        }
    }
    else if (Type == WEIXIN){
        switch (loginState) {
            case LoginSuccessful:
                //[[THud sharedInstance]showText:@"登录成功"];
                //[self loginThirdParty:openID NickName:[pInfo objectForKey:@"nickname"] Type:QQ Avatar:[pInfo objectForKey:@"headimgurl"]];
                NSLog(@"wx登录成功");
                [self thirdPartyLoginByOpenID:openID avatar:[pInfo objectForKey:@"headimgurl"] nickName:[pInfo objectForKey:@"nickname"] loginType:@"1" userType:@"1"];
                break;
                
            case LoginUserCancel:
                NSLog(@"wx取消了登录");
                //[[THud sharedInstance]showText:@"您取消了微信登录" Delay:2.0];
                break;
                
            case LoginNotNetwork:
                //[[THud sharedInstance]showText:@"网络异常，请检查网络连接"];
                NSLog(@"wx网络异常");
                break;
                
            case LoginFailure:
                //[[THud sharedInstance]showText:@"登录失败"];
                NSLog(@"wx登录失败");
                break;
                
            default:
                break;
        }
    }
//    else if (Type == WEIBO){
//        switch (loginState) {
//            case LoginSuccessful:
//                [[THud sharedInstance]showText:@"登录成功"];
//                [self loginThirdParty:[pInfo objectForKey:@"userID"] NickName:[pInfo objectForKey:@"screenName"] Type:WEIBO Avatar:[pInfo objectForKey:@"profileImageUrl"]];
//                break;
//                
//            case LoginUserCancel:
//                [[THud sharedInstance]showText:@"您取消了微信登录" Delay:2.0];
//                break;
//                
//            case LoginNotNetwork:
//                [[THud sharedInstance]showText:@"网络异常，请检查网络连接"];
//                break;
//                
//            case LoginFailure:
//                [[THud sharedInstance]showText:@"登录失败"];
//                break;
//                
//            default:
//                break;
//        }
//    }
}



-(void)backFn{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)remenberPW_:(UIButton *)sender{
    sender.selected = !sender.selected;
}

-(void)forgotPW_{
    wangjimimaViewController *vc = [wangjimimaViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//注册账号
- (void)doRegisterFn{
    RegUI*  ui=[[RegUI alloc] init];
    [self.navigationController pushViewController:ui animated:NO];
}

-(void)closeLoginPage{
    [self.navigationController popViewControllerAnimated:NO];
}

//点击登陆后的操作
- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    if (_remenberPW.selected) {
        NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
        [ud setValue:username forKey:@"username"];
        [ud setValue:password forKey:@"password"];
    }else{
        NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
        NSString *username = [ud objectForKey:@"username"];
        NSString *password = [ud objectForKey:@"password"];
        if (username.length !=0) {
            [ud removeObjectForKey:@"username"];
        }
        if (password.length !=0) {
            [ud removeObjectForKey:@"password"];
        }
    }
    [self showHudInView:self.view hint:NSLocalizedString(@"login.ongoing", @"Is Login...")];
    
    
    
    
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"/index.php/AppLoginUser/login"];
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    [req addPostValue:username forKey:@"mp"];
    [req addPostValue:password forKey:@"pwd"];
    [req startSynchronous];
    NSError *error = [req error];
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        NSString *response = [req responseString];
        NSLog(@"返回结果..%@",response);
        
        NSDictionary *dengluDIC =[NSMutableDictionary dictionaryWithDictionary:[response JSONValue]];
        NSLog(@"登录失败..%@",dengluDIC);
        NSString* _code=[dengluDIC objectForKey:@"code"];
        
        if([_code intValue]==7){//用户名或密码失败
            NSLog(@"登录失败..");
            UIAlertView * successTip = [[UIAlertView alloc] initWithTitle:@"信息提示:" message:@"用户名或密码错误，请重现登录！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [successTip show];
            [self hideHud];
        }
        if([_code intValue]==1){//登录成功
            
            
            //异步登陆账号
            [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:username
                                                                password:username
                                                              completion:
             ^(NSDictionary *loginInfo, EMError *error) {
                 [self hideHud];
                 if (loginInfo && !error) {
                     //获取群组列表
                     //[[EaseMob sharedInstance].chatManager asyncFetchMyGroupsList];
                     
                     //设置是否自动登录
                     [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
                     
                     //将2.1.0版本旧版的coredata数据导入新的数据库
                     EMError *error = [[EaseMob sharedInstance].chatManager importDataToNewDatabase];
                     if (!error) {
                         error = [[EaseMob sharedInstance].chatManager loadDataFromDatabase];
                     }
                     
                     //NSUserDefaults* ud=[[NSUserDefaults alloc] init];
                     //[ud setValue:username forKey:@"mp"];
                     NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
                     [accountDefaults setObject:username forKey:@"mp"];
                     [accountDefaults setObject:username forKey:@"phone"];
                     
                     //发送自动登陆状态通知
                     [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
                     
                     
                     
                     NSString* loginURL=HOST;
                     loginURL=[loginURL stringByAppendingString:@"index.php/AppLoginUser/login"];
                     NSURL* url=[[NSURL alloc] initWithString:loginURL];
                     ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
                     
                     
                     [req addPostValue:username forKey:@"mp"];
                     [req addPostValue:password forKey:@"pwd"];
                     NSLog(@"username:%@ pwd:%@",username,password);
                     [req startSynchronous];
                     NSError *asiError = [req error];
                     if (!asiError) {
                         AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                         [MBProgressHUD hideHUDForView:app.window animated:YES];
                         NSString *response = [req responseString];
                         NSLog(@"登录结果..%@",response);
                         
                         self.dic=[NSMutableDictionary dictionaryWithDictionary:[response JSONValue]];
                         NSLog(@"登录结果..%@",self.dic);
                         
                         NSString* uid=[self.dic objectForKey:@"id"];
                         uid=[NSString stringWithFormat:@"%@",uid];
                         
                         NSString*  mp=[self.dic objectForKey:@"mp"] ;
                         mp=[NSString stringWithFormat:@"%@",mp];
                         
                         NSLog(@"mp====%@,uid===%@",mp,uid);
                         
                         NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
                         [ud setValue:uid forKey:@"uid"];
                         [ud setValue:[self.dic objectForKey:@"user_type"] forKey:@"user_type"];
                         //[ud setValue:mp forKey:@"mp"];
                         
                         [self performSelectorOnMainThread:@selector(closeLoginPage) withObject:nil waitUntilDone:YES];
                     }
                     
                     
                 }else if([error.description isEqualToString:@"Already logged"]){
                     NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
                     [accountDefaults setObject:username forKey:@"mp"];
                     [accountDefaults setObject:username forKey:@"phone"];
                     
                     //发送自动登陆状态通知
                     [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
                     
                     
                     
                     NSString* loginURL=HOST;
                     loginURL=[loginURL stringByAppendingString:@"index.php/AppLoginUser/login"];
                     NSURL* url=[[NSURL alloc] initWithString:loginURL];
                     ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
                     
                     
                     [req addPostValue:username forKey:@"mp"];
                     [req addPostValue:password forKey:@"pwd"];
                     NSLog(@"username:%@ pwd:%@",username,password);
                     [req startSynchronous];
                     NSError *asiError = [req error];
                     if (!asiError) {
                         AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                         [MBProgressHUD hideHUDForView:app.window animated:YES];
                         NSString *response = [req responseString];
                         NSLog(@"登录结果..%@",response);
                         
                         self.dic=[NSMutableDictionary dictionaryWithDictionary:[response JSONValue]];
                         NSLog(@"登录结果..%@",self.dic);
                         
                         NSString* uid=[self.dic objectForKey:@"id"];
                         uid=[NSString stringWithFormat:@"%@",uid];
                         
                         NSString*  mp=[self.dic objectForKey:@"mp"] ;
                         mp=[NSString stringWithFormat:@"%@",mp];
                         
                         NSLog(@"mp====%@,uid===%@",mp,uid);
                         
                         NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
                         [ud setValue:uid forKey:@"uid"];
                         [ud setValue:[self.dic objectForKey:@"user_type"] forKey:@"user_type"];
                         //[ud setValue:mp forKey:@"mp"];
                         
                         [self performSelectorOnMainThread:@selector(closeLoginPage) withObject:nil waitUntilDone:YES];
                     }
                 }
                 else
                 {
                     switch (error.errorCode)
                     {
                         case EMErrorServerNotReachable:
                         TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                         break;
                         case EMErrorServerAuthenticationFailure:
                         TTAlertNoTitle(error.description);
                         break;
                         case EMErrorServerTimeout:
                         TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                         break;
                         default:
                         TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Logon failure"));
                         break;
                     }
                 }
             } onQueue:nil];

            
            
            
        }
    }
    
}

- (void)thirdPartyLoginByOpenID:(NSString *)openID avatar:(NSString *)avatar nickName:(NSString *)nickname loginType:(NSString *)loginType userType:(NSString *)userType{
{
    [self showHudInView:self.view hint:NSLocalizedString(@"login.ongoing", @"Is Login...")];
    
    
    
    
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"/index.php/openLogin/login"];
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    [req addPostValue:openID forKey:@"openid"];
    [req addPostValue:avatar forKey:@"avatar"];
    [req addPostValue:[NSString stringWithFormat:@"%@",nickname] forKey:@"nickname"];
    [req addPostValue:loginType forKey:@"login_type"];
    [req addPostValue:userType forKey:@"userType"];
    [req startSynchronous];
    NSError *error = [req error];
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        NSString *response = [req responseString];
        NSLog(@"返回结果..%@",response);
        
        NSDictionary *dengluDIC =[NSMutableDictionary dictionaryWithDictionary:[response JSONValue]];
        NSLog(@"登录失败..%@",dengluDIC);
        NSString* _code=[dengluDIC objectForKey:@"code"];
        
        if([_code intValue]==7){//用户名或密码失败
            NSLog(@"登录失败..");
            UIAlertView * successTip = [[UIAlertView alloc] initWithTitle:@"信息提示:" message:@"用户名或密码错误，请重现登录！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [successTip show];
            [self hideHud];
        }
        if([_code intValue]==1)
        {//登录成功
            
            NSUserDefaults *accountDefault = [NSUserDefaults standardUserDefaults];
            [accountDefault setObject:@"1" forKey:@"user_type"];
            [accountDefault setObject:[NSString stringWithFormat:@"%@",[dengluDIC objectForKey:@"id"]] forKey:@"uid"];
            
            
            //异步登陆账号
            [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:openID
                                                                password:openID
                                                              completion:
             ^(NSDictionary *loginInfo, EMError *error) {
                 [self hideHud];
                 if (loginInfo && !error) {
                     //获取群组列表
                     //[[EaseMob sharedInstance].chatManager asyncFetchMyGroupsList];
                     
                     //设置是否自动登录
                     [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
                     
                     //将2.1.0版本旧版的coredata数据导入新的数据库
                     EMError *error = [[EaseMob sharedInstance].chatManager importDataToNewDatabase];
                     if (!error) {
                         error = [[EaseMob sharedInstance].chatManager loadDataFromDatabase];
                     }
                     
                     //NSUserDefaults* ud=[[NSUserDefaults alloc] init];
                     //[ud setValue:username forKey:@"mp"];
                     NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
                     [accountDefaults setObject:openID forKey:@"mp"];
                     [accountDefaults setObject:openID forKey:@"phone"];
                     
                     //发送自动登陆状态通知
                     [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
                     
                     [self performSelectorOnMainThread:@selector(closeLoginPage) withObject:nil waitUntilDone:YES];
                     
                     
                     
                 }else if([error.description isEqualToString:@"Already logged"]){
                     NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
                     [accountDefaults setObject:openID forKey:@"mp"];
                     [accountDefaults setObject:openID forKey:@"phone"];
                     
                     //发送自动登陆状态通知
                     [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
                     
                     
                     
                         [self performSelectorOnMainThread:@selector(closeLoginPage) withObject:nil waitUntilDone:YES];

                 }
                 else
                 {
                     switch (error.errorCode)
                     {
                         case EMErrorServerNotReachable:
                             
                             [self registerE:openID];
//                             TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                             break;
                         case EMErrorServerAuthenticationFailure:
                             TTAlertNoTitle(error.description);
                             break;
                         case EMErrorServerTimeout:
                             TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                             break;
                         default:
                             TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Logon failure"));
                             break;
                     }
                 }
             } onQueue:nil];
            
            
            
            
        }
    }
    
}
}

-(void)registerE:(NSString *)openID{
    //异步注册账号
    [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:openID
                                                         password:openID
                                                   withCompletion:
     ^(NSString *username, NSString *password, EMError *error) {
         [self hideHud];
         
         if (!error) {
             
             //异步登陆账号
             [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:openID
                                                                 password:openID
                                                               completion:
              ^(NSDictionary *loginInfo, EMError *error) {
                  [self hideHud];
                  if (loginInfo && !error) {
                      //获取群组列表
                      //[[EaseMob sharedInstance].chatManager asyncFetchMyGroupsList];
                      
                      //设置是否自动登录
                      [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
                      
                      //将2.1.0版本旧版的coredata数据导入新的数据库
                      EMError *error = [[EaseMob sharedInstance].chatManager importDataToNewDatabase];
                      if (!error) {
                          error = [[EaseMob sharedInstance].chatManager loadDataFromDatabase];
                      }
                      
                      //NSUserDefaults* ud=[[NSUserDefaults alloc] init];
                      //[ud setValue:username forKey:@"mp"];
                      NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
                      [accountDefaults setObject:openID forKey:@"mp"];
                      [accountDefaults setObject:openID forKey:@"phone"];
                      
                      //发送自动登陆状态通知
                      [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
                      
                      [self performSelectorOnMainThread:@selector(closeLoginPage) withObject:nil waitUntilDone:YES];
                      
                      
                      
                  }else if([error.description isEqualToString:@"Already logged"]){
                      NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
                      [accountDefaults setObject:openID forKey:@"mp"];
                      [accountDefaults setObject:openID forKey:@"phone"];
                      
                      //发送自动登陆状态通知
                      [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
                      
                      
                      
                      [self performSelectorOnMainThread:@selector(closeLoginPage) withObject:nil waitUntilDone:YES];
                      
                  }
                  else
                  {
                      switch (error.errorCode)
                      {
                          case EMErrorServerNotReachable:
                              
                              
                              //                             TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                              break;
                          case EMErrorServerAuthenticationFailure:
                              TTAlertNoTitle(error.description);
                              break;
                          case EMErrorServerTimeout:
                              TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                              break;
                          default:
                              TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Logon failure"));
                              break;
                      }
                  }
              } onQueue:nil];

           
         }else{
             AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
             [MBProgressHUD hideHUDForView:app.window animated:YES];
             switch (error.errorCode) {
                 case EMErrorServerNotReachable:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                     break;
                 case EMErrorServerDuplicatedAccount:
                     TTAlertNoTitle(NSLocalizedString(@"register.repeat", @"You registered user already exists!"));
                     break;
                 case EMErrorServerTimeout:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                     break;
                 default:
                     TTAlertNoTitle(NSLocalizedString(@"register.fail", @"Registration failed"));
                     break;
             }
         }
     } onQueue:nil];

}

//弹出提示的代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView cancelButtonIndex] != buttonIndex) {
        //获取文本输入框
        UITextField *nameTextField = [alertView textFieldAtIndex:0];
        if(nameTextField.text.length > 0)
        {
            //设置推送设置
            [[EaseMob sharedInstance].chatManager setApnsNickname:nameTextField.text];
        }
    }
    //登陆
    [self loginWithUsername:_usernameTextField.text password:_passwordTextField.text];
}

//登陆账号
- (IBAction)doLogin:(id)sender {
    if (![self isEmpty]) {
        [self.view endEditing:YES];
        //支持是否为中文
        if ([self.usernameTextField.text isChinese]) {
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:NSLocalizedString(@"login.nameNotSupportZh", @"Name does not support Chinese")
                                  message:nil
                                  delegate:nil
                                  cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                                  otherButtonTitles:nil];
            
            [alert show];
            
            return;
        }
        /*
         #if !TARGET_IPHONE_SIMULATOR
         //弹出提示
         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"login.inputApnsNickname", @"Please enter nickname for apns") delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", @"Cancel") otherButtonTitles:NSLocalizedString(@"ok", @"OK"), nil];
         [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
         UITextField *nameTextField = [alert textFieldAtIndex:0];
         nameTextField.text = self.usernameTextField.text;
         [alert show];
         #elif TARGET_IPHONE_SIMULATOR
         [self loginWithUsername:_usernameTextField.text password:_passwordTextField.text];
         #endif
         */
        [self loginWithUsername:_usernameTextField.text password:_passwordTextField.text];
    }
}

//是否使用ip
- (IBAction)useIpAction:(id)sender
{
    UISwitch *ipSwitch = (UISwitch *)sender;
    [[EaseMob sharedInstance].chatManager setIsUseIp:ipSwitch.isOn];
}

//判断账号和密码是否为空
- (BOOL)isEmpty{
    BOOL ret = NO;
    NSString *username = _usernameTextField.text;
    NSString *password = _passwordTextField.text;
    if (username.length == 0 || password.length == 0) {
        ret = YES;
        [EMAlertView showAlertWithTitle:NSLocalizedString(@"prompt", @"Prompt")
                                message:NSLocalizedString(@"login.inputNameAndPswd", @"Please enter username and password")
                        completionBlock:nil
                      cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                      otherButtonTitles:nil];
    }
    
    return ret;
}


#pragma  mark - TextFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField == _usernameTextField) {
        _passwordTextField.text = @"";
    }
    
    return YES;
}

@end
